package com.dlna.client.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.LongClick;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.MediaController;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.dlna.client.R;
import com.dlna.client.activity.SocketClient.OnReceiveMessageListener;
import com.dlna.client.activity.base.BaseActivity;
import com.dlna.client.adapter.ImagePagerAdapter;
import com.dlna.client.adapter.ImagePagerAdapterV1;
import com.dlna.client.enity.DirInfo;
import com.dlna.client.enity.FileInfo;
import com.dlna.client.enity.MenuInfo;
import com.dlna.client.player.PlayerActivity;
import com.dlna.client.util.Constant;
import com.dlna.client.util.L;
import com.dlna.client.util.NetworkConnectivityListener;
import com.dlna.client.util.Util;
import com.dlna.client.util.XMLHelper;
import com.dlna.client.util.ZoomOutPageTransformer;
import com.dlna.client.view.AutoScrollViewPager;
import com.dlna.client.view.SystemBarTintManager;
import com.dlna.exception.MyExceptionHanlder;
import com.dlna.ftp.FtpClient;
import com.dlna.ftp.Notify;
import com.dlna.ftp.PollingService;
import com.dlna.ftp.PollingUtils;
import com.dlna.ftp.PreferenceHelper;
import com.viewpagerindicator.CirclePageIndicator;

@EActivity
public class MainActivityV1 extends BaseActivity implements
		OnReceiveMessageListener, OnClickListener, OnPageChangeListener,
		OnPreparedListener, OnErrorListener, OnCompletionListener {
	private static final String TAG = "MainActivity";
    private static String mRootPath=Constant.APP_PATH;//播放路径
    private static Boolean mFirstlyPlayer=false;//是否是第一次播放
	//View的初始化
	@ViewById(R.id.Image_left)
	ImageButton image_left;
	
	@ViewById(R.id.Image_right)
	ImageButton image_right;
	
	@ViewById(R.id.text_message)
	TextView textMessage;
	
	@ViewById(R.id.pager)
	AutoScrollViewPager localViewPager;

	@ViewById(R.id.indicator)
	CirclePageIndicator localIndicator;
	
	@ViewById(R.id.radio_dirs)
	RadioGroup mRadioGroup;
	
	@ViewById(R.id.radio_dirs_iner)
	RadioGroup mRadioGroup_iner;
	
	@ViewById(R.id.rl_local_display)
	RelativeLayout rlLocalDisplay;

    @ViewById(R.id.webViewBrowse)
    WebView webViewBrowse;
//	@ViewById
//	LinearLayout imageLayout;
//	
//	@ViewById
//	LinearLayout imageLayout_iner;
	
	private int menuPosition;
	private int inerMenuPosition;
	private Context mContext;
    private VideoView videoView;
    private MediaController mMediaController;
    private String mVideoName;
	
	/**
	 * 网络状态监听器
	 */
	private NetworkConnectivityListener mNetworkConnectivityListener;

	private ArrayList<FileInfo> localPictureList = new ArrayList<FileInfo>();

	private ArrayList<FileInfo> localVideoList = new ArrayList<FileInfo>();

	/**
	 * 本地资源、远程资源显示区域
	 */

	private ImagePagerAdapter localPagerAdapter;

	private ArrayList<DirInfo> localDirList = new ArrayList<DirInfo>();

	private MyBoradCast mBoradCast;


	/**
	 * 同步数据对话框
	 */
	private ProgressDialog progressDialog;
	
	
	@ViewById
	LinearLayout Layout_Radio,Layout_Radio_iner;
	
	

	private SystemBarTintManager tintManager = null;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
		MyExceptionHanlder handler = MyExceptionHanlder.getInstance();
	    handler.init(this); //在Appliction里面设置我们的异常处理器为UncaughtExceptionHandler处理器	
	    mFirstlyPlayer=true;
		int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;	    
		getWindow().getDecorView().setSystemUiVisibility(uiOptions);//隐藏底部任务栏代码	  
//		initNavigationBar();
		setContentView(R.layout.mainv1);		
		getMenus();
		//initPagerView();
		//get urls
		getUrls(mRootPath);		
		//滚动监听。。
		mBoradCast = new MyBoradCast();		
		IntentFilter mFilter = new IntentFilter();
		mFilter.addAction(Constant.CHANGE_DIRS);	
		mFilter.addAction(Constant.FTP_DOWNLOADED);
		registerReceiver(mBoradCast, mFilter);
		mContext=this;
		PollingUtils.startPollingService(this, 60, PollingService.class, PollingService.ACTION); 
		
		videoView=(VideoView) findViewById(R.id.videoView);
		mMediaController = new MediaController(this);
		mMediaController.setSystemUiVisibility(uiOptions);
		videoView.setMediaController(mMediaController);
		videoView.setOnPreparedListener(this);
		videoView.setOnErrorListener(this);
		videoView.setOnCompletionListener(this);
	}  
	
	private void initNavigationBar(){
		tintManager = new SystemBarTintManager(this);
		// enable status bar tint
		tintManager.setStatusBarTintEnabled(false);
		tintManager.setNavigationBarTintEnabled(false);
		// set a custom tint color for all system bars
		tintManager.setTintColor(Color.TRANSPARENT);
		tintManager.setNavigationBarTintColor(Color.TRANSPARENT);
	}
	
	
	/**
	 * 获取本地文件信息
	 */
	private void getLocalFileInfo() {
		// Util.getPictureFile(localPictureList, new File(Constant.APP_PATH),
		// MainActivity.this);
		Util.getDirectoryNames(localDirList, new File(Constant.APP_PATH));
		Util.getVideoFile(localVideoList, new File(Constant.APP_PATH),
				MainActivityV1.this);
	}

	
	
	/**
	 * 解析xml,,从文件夹Constant.APP_PATH{@link com.dlna.client.util.Constant}
	 * 
	 * xml 的名称必须为 menu.xml
	 * 
	 * 如果，末查找到，就取程序中默认的一个。（getResources().getAssets().open("menu.xml")）
	 * 
	 * 
	 * 
	 */
	private void getMenus(){
		
		XmlPullParserFactory factory;
		try {
			factory = XmlPullParserFactory.newInstance();
			XmlPullParser xmlPullParser = factory.newPullParser(); 
			if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
				textMessage.setText("内存卡不可以用");
				return;
			}
			if(mFirstlyPlayer){
				File file = new File(Constant.CLOUD_PATH + File.separator + "menu.xml");
				if(file.exists()){
				 	 //播放云文件夹
					 xmlPullParser.setInput(new FileInputStream(file),"UTF-8");
					 mRootPath=Constant.CLOUD_PATH;
				}else{
					//播放本地文件夹
					file=new File(Constant.APP_PATH + File.separator + "menu.xml");
					if(!file.exists()){
						Toast.makeText(this, "文件夹"+Constant.APP_PATH +"中找不到menu.xml", Toast.LENGTH_LONG).show();
						 xmlPullParser.setInput(getResources().getAssets().open("menu.xml"), "utf-8");
					}else{
						 xmlPullParser.setInput(new FileInputStream(file),"UTF-8");
					}
				}
				mFirstlyPlayer=false;
			}else{
				File file = new File(mRootPath + File.separator + "menu.xml");
				if(file.exists()){
					 xmlPullParser.setInput(new FileInputStream(file),"UTF-8");
				}else{
					//播放本地文件夹
					file=new File(Constant.APP_PATH + File.separator + "menu.xml");
					if(!file.exists()){
						Toast.makeText(this, "文件夹"+Constant.APP_PATH +"中找不到menu.xml", Toast.LENGTH_LONG).show();
						 xmlPullParser.setInput(getResources().getAssets().open("menu.xml"), "utf-8");
					}else{
						 xmlPullParser.setInput(new FileInputStream(file),"UTF-8");
						 mRootPath=Constant.APP_PATH;
					}
				}				
			}			
			
		    menus = XMLHelper.parseMenu(xmlPullParser,mRootPath);    
		    L.e("menus---->size"+menus.size());   
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		
		initPicAndText();
         //xmlPullParser.setInput(new StringReader(xmlString));
         
         
	}
	
	
	
	/**
	 * 返回按钮点击事件
	 */
	void backToMenus(){
		menuPosition = 0;
		inerMenuPosition = -1;
		
		Layout_Radio_iner.setVisibility(View.GONE);
		mRadioGroup_iner.clearCheck();
		Layout_Radio.setVisibility(View.VISIBLE);
		YoYo.with(Techniques.BounceInLeft)
	    .duration(700)
	    .playOn(Layout_Radio);
		
		mRadioGroup.check(getId(false, 0));
//		pagerAdapter.upData(menus.get(menuPosition).menus == null ?menus.get(menuPosition).picList : menus.get(menuPosition).menus.get(inerMenuPosition).picList);
		localIndicator.setCurrentItem(0);
		startAutoViewPager();
	}
	
	/**
	 * 向左切换按钮
	 */
	@Click
	void Image_left(){
		int currentItem = localIndicator.getCurrentItem();
		if(currentItem > 0 ){
			localIndicator.setCurrentItem(--currentItem);
		}
	}
	
	/**
	 * 向右切换按钮
	 */
	@Click
	void Image_right(){
		int currentItem = localIndicator.getCurrentItem();
		if(currentItem >= 0 && currentItem < pagerAdapter.getCount()-1){
			++currentItem;
			localIndicator.setCurrentItem(currentItem);
		}
		
		
		
		
		
//		
//		if(currentItem>0 && currentItem<localPictureList.size()){
//			if (currentItem+1==localPictureList.size()) {
//				RadioButton mRadioButton = (RadioButton) findViewById(mRadioGroup.getCheckedRadioButtonId());
//				int currentIndex = mRadioGroup.indexOfChild(mRadioButton);
//				int nextIndex = currentIndex == localDirList.size() - 1 ? 0
//						: ++currentIndex;
//				mRadioGroup
//						.check(mRadioGroup.getChildAt(nextIndex).getId());
//			} else {
//				++currentItem;
//				localIndicator.setCurrentItem(currentItem);
//			}
//		}
	}

    /**
     * 产品视频
     */
	@Click
    void HexingMall(){
		mRadioGroup.clearCheck();	
   	 	stoptAutoPlay();
   	    stopVideoView();
   	 	Toast.makeText(this, "正在加载视频...", Toast.LENGTH_LONG).show();
   	    mVideoName="产品视频";
   	    startVideoView();
       
    }

    /**
     * 形象展示
     */
    @Click
    void DayongMeishuguan(){
    	mRadioGroup.clearCheck();	
   	 	stoptAutoPlay();
   	    stopVideoView();
   	 	Toast.makeText(this, "正在加载视频...", Toast.LENGTH_LONG).show();
   	    mVideoName="形象展示";
   	    startVideoView();
    }

    /**
     * webview 加载
     */
    WebViewClient webViewClient = new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            progressDialog.dismiss();
            super.onPageFinished(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }
    };
	/**
	 * 长按退出
	 */
	@LongClick 
	void Layout_Title(){
		finish();
		//showSettingDialog(mContext);
	}
	
	/**
	 *解析文件中的图片和文字 及其对应关系 
	 */
	@Background
	void initPicAndText(){
		for (int i = 0; i < menus.size(); i++) {
			if(menus.get(i).menus != null){
				ArrayList<MenuInfo> inerMenus = menus.get(i).menus;
				for (int j = 0; j < inerMenus.size(); j++) {
					inerMenus.get(j).picList = Util.getPictureFile(new File(inerMenus.get(j).DirPath));
					if(inerMenus.get(j).picList.size() == 0){
						inerMenus.get(j).error = true;
						inerMenus.get(j).errorMsg = inerMenus.get(j).menuName +"下无图片";
					}
				}
			}else{
				menus.get(i).picList = Util.getPictureFile(new File(menus.get(i).DirPath));
				if(menus.get(i).picList.size() == 0){
					menus.get(i).error = true;
					menus.get(i).errorMsg = menus.get(i).menuName +"下无图片";
				}
			}
		}
		L.e("menus----"+menus.size());
		initMenuViews();
		initViewPager();
	}
	
	/**
	 * 动态生成一层按钮
	 */
	@UiThread
	void initMenuViews(){
		mRadioGroup.removeAllViews();
		RadioButton[] menuViews = new RadioButton[menus.size()];
		for (int i = 0; i < menus.size(); i++) {
			LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
			lp.weight = 1;
			menuViews[i]= (RadioButton) getLayoutInflater().inflate(R.layout.main_radiobutton, mRadioGroup,false);
			menuViews[i].setText(menus.get(i).menuName);
			menuViews[i].setId(getId(false, i));
			mRadioGroup.addView(menuViews[i]);
		}
		mRadioGroup.setOnCheckedChangeListener(new onCheckChangeListener(false));
	}
	
	/**
	 * 动态创建二级按钮
	 * @param menus
	 */
	void initInerMenu(ArrayList<MenuInfo> menus){
//		imageLayout_iner.removeAllViews();
		mRadioGroup_iner.removeAllViews();
		RadioButton[] menuViews = new RadioButton[menus.size()];
		TextView textBack = new TextView(this);
		mRadioGroup_iner.setOnCheckedChangeListener(new onCheckChangeListener(true));
		for (int i = 0; i < menus.size(); i++) {
			menuViews[i]= (RadioButton) getLayoutInflater().inflate(R.layout.main_radiobutton, mRadioGroup_iner,false);
//			if(i == 0)
//				menuViews[i].setText("返回");
//			else 
			android.widget.RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT);
			lp.weight = 1;
			if(i == 0){
				textBack.setText("< 返回");
				textBack.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
				textBack.setTextColor(getResources().getColorStateList(R.color.menu_text_color));
				textBack.setBackgroundResource(R.drawable.back_bg);
				textBack.setGravity(Gravity.CENTER);
				textBack.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						backToMenus();
					}
				});
				mRadioGroup_iner.addView(textBack,lp);
			}
			menuViews[i].setText(menus.get(i).menuName);
			menuViews[i].setId(getId(true, i));
			mRadioGroup_iner.addView(menuViews[i],lp);
//			if(i== 0){
//				menuViews[i].setChecked(true);
//			}
		}
	}
	
	/**
	 * 生成View 的id
	 * @param iner
	 * @param position
	 * @return
	 */
	private int getId(boolean iner,int position){
		if(iner){
			return position + 1234;
		}else{
			return position + 4321;
		}
	}
	
	
	private int getPosition (boolean iner,int id){
		if(iner){
			return id - 1234;
		}else{
			return id - 4321;
		}
	}
	
	/**
	 * 初始化滚动视图 
	 */
	@UiThread
	void initViewPager(){
		pagerAdapter = new ImagePagerAdapterV1(this, menus.get(0).menus!= null?menus.get(0).menus.get(0).picList:menus.get(0).picList);
		localViewPager.setAdapter(pagerAdapter);
		localViewPager.setPageTransformer(true, new ZoomOutPageTransformer());
		localIndicator.setViewPager(localViewPager);
		localIndicator.setOnPageChangeListener(this);
		//localViewPager.setOnPageChangeListener(this);
		mRadioGroup.check(getId(false, 0));
//		if(menus.get(0).menus != null){
//			menuPosition = 0;
//			inerMenuPosition = 0;
//		}else{
//			menuPosition = 0;
//			inerMenuPosition = -1;
//		}
		startAutoViewPager();
	}
	
	/**
	 * 启动 Viewpager 自动切换  
	 */
	private void startAutoViewPager(){
		localViewPager.setInterval(Constant.AUTO_PLAY_INTERVAL);
		localViewPager.startAutoScroll();
	}
	

	/**
	 * 停止自动播放
	 */
	private void stoptAutoPlay() {
		localViewPager.stopAutoScroll();
	}

	@Override
	protected void onResume() {
		// initCalendar();
		super.onResume();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		stoptAutoPlay();
		PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION); 
		if (mBoradCast != null) {
			unregisterReceiver(mBoradCast);
			mBoradCast = null;
		}
//		socketClient.disConnect();
		System.exit(0);
	}









	private ArrayList<MenuInfo> menus;

//	private ImageView[] images;
//
//	public ImageView[] images_iner;

	private ImagePagerAdapterV1 pagerAdapter;
	private ArrayList<String> urls;



	@Override
	public void notifyVideoStart(int pos) {
		if (PlayerActivity.instance != null)
			PlayerActivity.instance.onVideoStart(pos);
	}

	@Override
	public void notifyVideoPause(int pos) {
		if (PlayerActivity.instance != null)
			PlayerActivity.instance.onVideoPause(pos);
	}

	@Override
	public void notifyVideoSeekTo(int pos) {
		if (PlayerActivity.instance != null)
			PlayerActivity.instance.onVideoSeekTo(pos);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {

		}

		return super.onKeyDown(keyCode, event);

	};

	@Override
	public void notifyVideoStop() {
		if (PlayerActivity.instance != null)
			PlayerActivity.instance.finish();
	}

	
	public class MyBoradCast extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getAction().equals(Constant.CHANGE_DIRS)) {
				if (mRadioGroup != null) {
					if(inerMenuPosition == -1){
						int nextMenuPosition = menuPosition == menus.size() -1 ? 0:++menuPosition;
//						if(menus.get(nextMenuPosition).menus != null){
						mRadioGroup.check(getId(false, nextMenuPosition));
						if(nextMenuPosition==0){
							Layout_Radio_iner.setVisibility(View.GONE);
							Layout_Radio.setVisibility(View.VISIBLE);
							YoYo.with(Techniques.ZoomInLeft)
						    .duration(700)
						    .playOn(Layout_Radio);		
							
							//modify by jyy 2015/08/17 循环播放云和本地文件夹{{{
							if(Constant.APP_PATH.equals(mRootPath)){
								mRootPath=Constant.CLOUD_PATH;
							}else{
								mRootPath=Constant.APP_PATH;
							}
							getMenus();			
							getUrls(mRootPath);	
							//}}}
							/*pagerAdapter.upData(menus.get(nextMenuPosition).menus == null ?menus.get(nextMenuPosition).picList : menus.get(nextMenuPosition).menus.get(0).picList);
							localIndicator.setCurrentItem(0);
							startAutoViewPager();*/
						}
//						}else{
//							
//						}
					}else{
						int innerNextMenuPosition = inerMenuPosition == menus.get(menuPosition).menus.size()-1  ? 0:++inerMenuPosition;
						/*if(innerNextMenuPosition == 0){
							int nextMenuPosition = menuPosition == menus.size() -1 ? 0:++menuPosition;
							mRadioGroup.check(getId(false, nextMenuPosition));	
							
							Layout_Radio_iner.setVisibility(View.GONE);
							Layout_Radio.setVisibility(View.VISIBLE);
							YoYo.with(Techniques.ZoomInLeft)
						    .duration(700)
						    .playOn(Layout_Radio);
							
							pagerAdapter.upData(menus.get(menuPosition).menus == null ?menus.get(menuPosition).picList : menus.get(menuPosition).menus.get(inerMenuPosition).picList);
							localIndicator.setCurrentItem(0);
							startAutoViewPager();
							
							inerMenuPosition = -1;*/
						// add by jyy 2015/07/14
						if(innerNextMenuPosition == 0){
							int nextMenuPosition = menuPosition == menus.size() -1 ? 0:++menuPosition;
							mRadioGroup.check(getId(false, nextMenuPosition));	
							if(nextMenuPosition==0){
								Layout_Radio_iner.setVisibility(View.GONE);
								Layout_Radio.setVisibility(View.VISIBLE);
								YoYo.with(Techniques.ZoomInLeft)
							    .duration(700)
							    .playOn(Layout_Radio);		
								
								//modify by jyy 2015/08/17 循环播放云和本地文件夹{{{
								if(Constant.APP_PATH.equals(mRootPath)){
									mRootPath=Constant.CLOUD_PATH;
								}else{
									mRootPath=Constant.APP_PATH;
								}
								getMenus();			
								getUrls(mRootPath);	
								//}}}
								/*pagerAdapter.upData(menus.get(nextMenuPosition).menus == null ?menus.get(nextMenuPosition).picList : menus.get(nextMenuPosition).menus.get(0).picList);
								localIndicator.setCurrentItem(0);
								startAutoViewPager();*/
							}
							inerMenuPosition = -1;
							//}}}
//							if(menus.get(nextMenuPosition).menus != null){
						}else{
							mRadioGroup_iner.check(getId(true, inerMenuPosition));
						}
					}
					
					
//					RadioButton mRadioButton = (RadioButton) findViewById(mRadioGroup
//							.getCheckedRadioButtonId());
//					int currentIndex = mRadioGroup.indexOfChild(mRadioButton);
//					int nextIndex = currentIndex == localDirList.size() - 1 ? 0
//							: ++currentIndex;
//					mRadioGroup.check(mRadioGroup.getChildAt(nextIndex).getId());
				}
			}else if(Constant.FTP_DOWNLOADED.equals(intent.getAction())){
				/*getMenus();			
				getUrls(mRootPath);		*/		
			}
		}
	}

	
	
	private class onCheckChangeListener implements OnCheckedChangeListener {
		private boolean iner;

		public onCheckChangeListener(boolean iner) {
			this.iner = iner;
		}

		@Override
		public void onCheckedChanged(RadioGroup arg0, int arg1) {
			// TODO Auto-generated method stub
			L.d("------onCheck-------"+arg1);
            if(webViewBrowse != null){
                int visible = webViewBrowse.getVisibility();
                if(visible != View.GONE){
                    webViewBrowse.setVisibility(View.GONE);
                    webViewBrowse.loadDataWithBaseURL(null, "","text/html", "utf-8",null);
                }
            }
            if(videoView!=null){
            	int visible = videoView.getVisibility();
                if(visible != View.GONE){
                	stopVideoView();
                	videoView.setVisibility(View.GONE);                	
                }
            }
			if (iner) {
				if(arg1 == -1) return;
				int tag = getPosition(true, arg1);
				L.d("iner------------------>"+tag);
				// L.d("tag----->"+tag);
				inerMenuPosition = tag;
//				if(tag == 0){
//					Layout_Radio_iner.setVisibility(View.GONE);
//					Layout_Radio.setVisibility(View.VISIBLE);
//					YoYo.with(Techniques.BounceInLeft)
//				    .duration(700)
//				    .playOn(Layout_Radio);
//					
//					pagerAdapter.upData(menus.get(menuPosition).menus == null ?menus.get(menuPosition).picList : menus.get(menuPosition).menus.get(inerMenuPosition).picList);
//					localIndicator.setCurrentItem(0);
//					startAutoViewPager();
//				}else{
					if(menus.get(menuPosition).error){
						textMessage.setText(menus.get(menuPosition).errorMsg);
						return;
					}else{
						textMessage.setText("");
					}
					pagerAdapter.upData(menus.get(menuPosition).menus == null ?menus.get(menuPosition).picList : menus.get(menuPosition).menus.get(inerMenuPosition).picList);
					localIndicator.setCurrentItem(0);
					startAutoViewPager();
//				}
				
			} else {
				if(arg1 == -1){return;} 
				int tag = getPosition(false, arg1);
				
				L.d("out------------------>"+tag);
				menuPosition = tag;
				if(menus.get(menuPosition).menus != null){
					initInerMenu(menus.get(menuPosition).menus);
					
					Layout_Radio.setVisibility(View.GONE);
					mRadioGroup.clearCheck();
					
					
					Layout_Radio_iner.setVisibility(View.VISIBLE);
					YoYo.with(Techniques.BounceInRight)
				    .duration(700)
				    .playOn(Layout_Radio_iner);
					setCheckFirst();
					
					
				}else{
					if(menus.get(menuPosition).error){
						textMessage.setText(menus.get(menuPosition).errorMsg);
						return;
					}else{
						textMessage.setText("");
					}
					
					pagerAdapter.upData(menus.get(menuPosition).picList);
					localIndicator.setCurrentItem(0);
					startAutoViewPager();
					inerMenuPosition = -1;
				}
			}
		}
	}
	
	@UiThread(delay = 1000)
	void setCheckFirst(){
		inerMenuPosition = 0;
		mRadioGroup_iner.check(getId(true, inerMenuPosition));
	}
	
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}

//	private void changeViewBg(int position){
//		for (int i = 0; i < menus.size(); i++) {
//			if(i == position){
//				images[i].setBackgroundResource(R.drawable.on);;
//			}else{
//				images[i].setBackgroundResource(R.drawable.off);
//			}
//		}
//	}
	

	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int arg0) {
		
	}

	@Override
	public void onReceiveMessage(byte messageID, byte[] message) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void notifyOnline() {
		// TODO Auto-generated method stub
	}

	@Override
	public void notifyOffline() {
		// TODO Auto-generated method stub
	}

	@Override
	public void notifyInControl() {
		// TODO Auto-generated method stub
	}

	@Override
	public void notifyNoControl() {
		// TODO Auto-generated method stub
	}

	@Override
	public void notifySyncfile(byte[] message) {
		// TODO Auto-generated method stub
	}

	@Override
	public void notifyCheckfile(byte[] message) {
		// TODO Auto-generated method stub
	}

	@Override
	public void notifySyncfileCancel() {
		
	}
	
	private void getUrls(String rootPath){
			
		XmlPullParserFactory factory;
		try {
			factory = XmlPullParserFactory.newInstance();
			XmlPullParser xmlPullParser = factory.newPullParser(); 
			if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
				textMessage.setText("内存卡不可以用");
		    return;
		}
		File file = new File(rootPath + File.separator + "url.xml");
		if(!file.exists()){
			Toast.makeText(this, "文件夹"+rootPath +"中找不到url.xml", Toast.LENGTH_LONG).show();
			 xmlPullParser.setInput(getResources().getAssets().open("url.xml"), "utf-8");
		}else{
			 xmlPullParser.setInput(new FileInputStream(file),"UTF-8");
		}
		urls = XMLHelper.parseUrl(xmlPullParser);   
		if(urls==null||urls.size()!=2){
			Toast.makeText(this, "文件夹"+rootPath +"中url.xml,数据错误", Toast.LENGTH_LONG).show();
			return;
		}
	    L.e("urls---->size"+urls.size());   
	} catch (XmlPullParserException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
	}
	
	private void showSettingDialog(Context context) {  
        LayoutInflater inflater = LayoutInflater.from(this);  
        final View textEntryView = inflater.inflate(  
                R.layout.setting, null);  
        final EditText edtHost=(EditText)textEntryView.findViewById(R.id.edtHost);  
        final EditText edtUsername=(EditText)textEntryView.findViewById(R.id.edtUsername); 
        final EditText edtPasswd=(EditText)textEntryView.findViewById(R.id.edtPasswd); 
        final EditText edtPort=(EditText)textEntryView.findViewById(R.id.edtPort); 
        
        if(Util.isNotBlank(PreferenceHelper.getHost(mContext))){
        	edtHost.setText(PreferenceHelper.getHost(mContext));
        }
        if(Util.isNotBlank(PreferenceHelper.getUsername(mContext))){
        	edtUsername.setText(PreferenceHelper.getUsername(mContext));
        }
        if(Util.isNotBlank(PreferenceHelper.getPassword(mContext))){
        	edtPasswd.setText(PreferenceHelper.getPassword(mContext));
        }
        if(Util.isNotBlank(PreferenceHelper.getPort(mContext))){
        	edtPort.setText(PreferenceHelper.getPort(mContext));
        }
        
        final AlertDialog.Builder builder = new AlertDialog.Builder(context);  
        builder.setCancelable(false);  
       /* builder.setIcon(R.drawable.); */ 
        builder.setTitle("FTP服务配置");  
        builder.setView(textEntryView);  
        builder.setPositiveButton("退出",  
                new DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int whichButton) {                    	
						try {
							 /*Field field = dialog.getClass()  
							        .getSuperclass().getDeclaredField(  
							        "mShowing" );
							 field.setAccessible( true );  
                             // 将mShowing变量设为false，表示对话框已关闭   
                             field.set(dialog, true );  
                             dialog.dismiss();*/
                             finish();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}  
                               
                    	
                    }  
                });  
        builder.setNeutralButton("确定",  
                new DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int whichButton) {  
                    	
						try {
							Field field = dialog.getClass()  
							        .getSuperclass().getDeclaredField(  
							        "mShowing" );
							  field.setAccessible( true );  
                              // 将mShowing变量设为false，表示对话框已关闭   
                              field.set(dialog, false ); 
						} catch (Exception e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} 
						boolean isCheck=true;
                               
                    	if(!(edtHost.getText()!=null&&Util.isNotBlank(edtHost.getText().toString()))){
                    		Notify.toast(mContext, "请输入FTP服务器地址.",3000);  
                    		isCheck=false;
                    	}
                    	if(!(edtPort.getText()!=null&&Util.isNotBlank(edtPort.getText().toString()))){
		               		 Notify.toast(mContext, "请输入端口.",3000);
		               		isCheck=false;
		               		
                      	}
                    	if(!(edtUsername.getText()!=null&&Util.isNotBlank(edtUsername.getText().toString()))){
                    		 Notify.toast(mContext, "请输入密码.",3000);
                    		 isCheck=false;
                    		 
                    	}
                    	if(!(edtPasswd.getText()!=null&&Util.isNotBlank(edtPasswd.getText().toString()))){
                    		 Notify.toast(mContext, "请输入用户名.",3000);
                    		 isCheck=false;                    		 
                    	}
                    	if(isCheck){
                    		PreferenceHelper.setHost(mContext, edtHost.getText().toString().trim());
                        	PreferenceHelper.setPort(mContext, edtPort.getText().toString().trim());
                        	PreferenceHelper.setUsername(mContext, edtUsername.getText().toString().trim());
                        	PreferenceHelper.setPassword(mContext, edtPasswd.getText().toString().trim());
                        	try {                    		 
                        		
                    			/*final String username=edtUsername.getText().toString();
                    			final String password=edtPasswd.getText().toString();
                    			int port=21;
                    			String host=edtHost.getText().toString();
                    			String rootDirectory="WiremeCloud";
                    			final URL url=new URL("ftp",host,port,rootDirectory);
                    			new Thread(new Runnable() {           
                                    @Override  
                                    public void run() {                                 	
                                    	FtpClient.download(url, username, password);
                                    }
                    			}).start();*/ 
                        		Field field = dialog.getClass()  
    							        .getSuperclass().getDeclaredField(  
    							        "mShowing" );
     							 field.setAccessible( true );  
                                  // 将mShowing变量设为false，表示对话框已关闭   
                                 field.set(dialog, true);  
                                 dialog.dismiss();
                    			
                    		} catch (Exception e) {
                    			Log.e("file", e.getMessage());
                    		}       
                    	}
                    	
                    }  
                });  
        builder.setNegativeButton("连接测试",  
                new DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int whichButton) {                      	
                    	try {
                    		Field field = dialog.getClass()  
                                    .getSuperclass().getDeclaredField(  
                                    "mShowing" );  
                                    field.setAccessible( true );  
                                    // 将mShowing变量设为false，表示对话框已关闭   
                                    field.set(dialog, false );  
                            boolean isCheck=true;
                            if(!(edtHost.getText()!=null&&Util.isNotBlank(edtHost.getText().toString()))){
                        		Notify.toast(mContext, "请输入FTP服务器地址.",3000);
                        		isCheck=false;
                        	}
                        	if(!(edtPort.getText()!=null&&Util.isNotBlank(edtPort.getText().toString()))){
    		               		 Notify.toast(mContext, "请输入端口.",3000);
    		               		isCheck=false;
                          	}
                        	if(!(edtUsername.getText()!=null&&Util.isNotBlank(edtUsername.getText().toString()))){
                        		 Notify.toast(mContext, "请输入密码.",3000);
                        		 isCheck=false;
                        	}
                        	if(!(edtPasswd.getText()!=null&&Util.isNotBlank(edtPasswd.getText().toString()))){
                        		 Notify.toast(mContext, "请输入用户名.",3000);
                        		 isCheck=false;
                        	}
                            if(isCheck){
                            	String host=edtHost.getText().toString().trim();
                    			final String username=edtUsername.getText().toString().trim();
                    			final String password=edtPasswd.getText().toString().trim();
                    			String temPort=edtPort.getText().toString().trim();       			
                    			if(!Util.isNotBlank(temPort)){
                    				temPort="21";
                    			}
                    			final int port= Integer.valueOf(temPort);                			
                    			String rootDirectory="WiremeCloud";
                    			final URL url=new URL("ftp",host,port,rootDirectory);
                    			new Thread(new Runnable() {           
                                    @Override  
                                    public void run() {                                 	
                                    	if(FtpClient.downloadTest(url, username, password)){
                                    		Looper.prepare();
                                    		Notify.toast(mContext, "FTP服务器测试连接成功！", 3000); 
                                    		Looper.loop();
                                    	}else{
                                    		Looper.prepare();
                                    		Notify.toast(mContext, "FTP服务器测试连接失败！", 3000);
                                    		Looper.loop();
                                    	}
                                    }
                    			}).start();
                            }                        	
                			
                		} catch (Exception e) {
                			Log.e("file", e.getMessage());
                		}                   	
                         
                    }  
                });  
        AlertDialog dialog=builder.show();  
    } 
	
	/**
	 * 播放视频
	 * @param videoName
	 */
	private void startVideoView(){
		if(!Util.isNotBlank(mVideoName)){
			return;
		}			
		File file = new File(Constant.APP_PATH + File.separator + Constant.PATH_VIDEOS+File.separator+mVideoName+".mp4");
		if(!file.exists()){
			Toast.makeText(this, "文件夹"+Constant.APP_PATH +"中找不到"+Constant.PATH_VIDEOS, Toast.LENGTH_LONG).show();		 
		}else{
			videoView.setVisibility(View.VISIBLE);
			videoView.setVideoPath(file.getPath());			
			videoView.start();
		}
	}
	
	
	private void stopVideoView()
    {
        if (null != videoView)
        {
        	videoView.seekTo(0);
        	videoView.stopPlayback();
        }
    }

	@Override
	public void onCompletion(MediaPlayer arg0) {
		stopVideoView();        
        startVideoView();
		
	}

	@Override
	public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onPrepared(MediaPlayer arg0) {
		videoView.start();
		
	}
	

}